﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dos.Common;
using Dos.ORM;
using Model;
using System.Data.Common;
using System.Data;

using System.IO;
using System.Security.Cryptography;
using System.Xml;
using Newtonsoft.Json.Linq;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Net;
using System.Web.Configuration;
using Common;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Sample.CommonService.TemplateMessage.WxOpen;
using System.Text.RegularExpressions;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;

namespace Business
{
    public class KqLogic
    {

        public static string up_step_max_time = "up_step_max_time";


        public static string step_add = "step_add"; // 这个是 dk 赠送 %比 步数
        public static string fx_step_add = "fx_step_add"; // 这个是特别团分享给新用户后增加步数送KB
        public static string fxstep_10000 = "fxstep_10000";
        public static string jstype_10000 = "10000"; // 
        public static int qdday_10 = 7; // 连续几天签到赠送

        public static readonly string AppId = WebConfigurationManager.AppSettings["WxOpenAppId"];

        public static int day_kb = 1;

        public static int day_kb_max = 3;

        public static string get_dkurl()
        {
            return "http://112.74.107.85:111/DataServer.asmx/";
        }

        public static void log(string msg, string pn = null)
        {
            Dos.Common.LogHelper.Error(msg, pn);
        }

        /// <summary>
        /// 发送SOAP请求，并返回响应xml
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="datastr">SOAP请求信息</param>
        /// <returns>返回响应信息</returns>
        public static string GetSOAPReSource(string url, string datastr)
        {

            //发起请求
            Uri uri = new Uri(url);
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "text/xml; charset=utf-8";
            webRequest.Method = "POST";
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
                requestStream.Write(paramBytes, 0, paramBytes.Length);
            }

            //响应
            WebResponse webResponse = webRequest.GetResponse();
            using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
            {
                string result = "";
                return result = myStreamReader.ReadToEnd();
            }
        }

        public static DateTime GetTsDate(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dt = dtStart.Add(toNow);
            return dt;
        }

        #region dk接口

        private static string http_dkjk(string para,yd_jk_log yjl)
        {
            string url = get_dkurl() + para;
            if (yjl != null) {
                yjl.url = url;
                yjl.credate = DateTime.Now;
            }
            
            string json = "";
            try
            {
                json = HttpHelper.Get(url);
                
                if (yjl != null)
                {
                    yjl.res = json;
                    Db.GetDbLog().Insert(yjl);
                }
                
                //KqLogic.log(url + json, "jk_");
            }
            catch (Exception ex)
            {
                if (yjl != null)
                {
                    yjl.res = "ex-" + ex.ToString();
                }
                
                Db.GetDbLog().Insert(yjl);
                //KqLogic.log("http_dkjk_error: " + url + " -- " + ex.ToString(),"jk_");
                return "{result:false}";
            }


            XmlDocument xml = new XmlDocument();
            xml.LoadXml(json);
            json = xml.InnerText;
            return json;

            
        }

        private static string http_dkjk(string urlname, string para)
        {
            //发起请求
            string url = get_dkurl() + urlname;
            Uri uri = new Uri(url);
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "application/soap+xml; charset=utf-8";
            webRequest.Method = "POST";
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                byte[] paramBytes = Encoding.UTF8.GetBytes(para);
                requestStream.Write(paramBytes, 0, paramBytes.Length);
            }
            string json = "";
            //响应
            WebResponse webResponse = webRequest.GetResponse();
            using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
            {
                json = myStreamReader.ReadToEnd();
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(json);
                json = xml.InnerText;
                return json;
            }
        }

        private static string http_dkjk_post(string para, object p)
        {
            string url = get_dkurl() + para;
            KqLogic.log(url);
            string json = HttpHelper.Post(url, p);
            KqLogic.log(url + json);
            //string json = "{re:true}";
            return json;
        }



        //dk接口调用
        public static Jr dkjk_user_phone(string city, string phone, string openid, string unionId)
        {
            string para = "GetMyInforByUnionID?city=" + city + "&mobilephone=" + phone + "&openid=" + openid + "&unionid=" + unionId;
            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "GetMyInforByUnionID";
            yjl.oldurl = para;
            yjl.phone = phone;
            yjl.uid = 0;
            string json = http_dkjk(para, yjl);
            json = get_user_json(json);
            return new Jr(json);
        }

        private static string get_user_json(string json)
        {
            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            int uid = 0;
            string openid = "";
            string MobilePhone = "";
            int consume_give_kb = 0;
            int Integral = 0;
            if (bl)
            {
                json = jo["data"]["rows"].ToString();
                JArray ja = JArray.Parse(json);
                for (var i = 0; i < ja.Count; i++)
                {
                    jo = JObject.Parse(ja[i].ToString());

                    openid = jo["OpenID"].ToString();
                    //if (!string.IsNullOrWhiteSpace(openid))
                    //{
                    uid = Convert.ToInt32(jo["ID"].ToString());
                    string gk = jo["consume_give_kb"].ToString();
                    consume_give_kb = 0;
                    if (!string.IsNullOrWhiteSpace(gk))
                    {
                        consume_give_kb = Convert.ToInt32(gk);
                    }

                    string ig = jo["Integral"].ToString();
                    Integral = 0;
                    if (!string.IsNullOrWhiteSpace(ig))
                    {
                        Integral = Convert.ToInt32(ig);
                    }
                    MobilePhone = jo["MobilePhone"].ToString();
                    break;
                    //}
                }
            }
            json = Dos.Common.JSON.ToJSON(new { success = bl, uid = uid, openid = openid, kball = consume_give_kb, kbnow = Integral, MobilePhone = MobilePhone });
            KqLogic.log(json);
            return json;
        }




        public static Jr dkjk_user_uid(string city, int uid)
        {
            //构造soap请求信息
            //StringBuilder soap = new StringBuilder();
            //soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            //soap.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            //soap.Append("<soap:Body>");
            //soap.Append("<GetMyInfor xmlns=\"http://tempuri.org/\">");
            //soap.Append("<city>"+city+"</city>");
            //soap.Append("<uid>" + uid.ToString() + "</uid>");
            //soap.Append("</GetMyInfor>");
            //soap.Append("</soap:Body>");
            //soap.Append("</soap:Envelope>");

            string para = "GetMyInfor?city=" + city + "&uid=" + uid.ToString();

            //yd_jk_log yjl = new yd_jk_log();
            //yjl.name = "GetMyInfor";
            //yjl.oldurl = para;
            //yjl.phone = "";
            //yjl.uid = uid;
            
            yd_jk_log yjl = null;

            string json = http_dkjk(para, yjl);

            //string json = http_dkjk("GetMyInfor", soap.ToString());
            json = get_user_json(json);
            return new Jr(json);
        }


        //发送验证码接口名称已经改了
        //接口名称:SendMobileCode
        //参数: 
        //参数1:openid(字符串 openid)
        //参数2:ipaddr(字符串 ip地址)
        //参数3:mobile(字符串 手机号码)
        //参数4:city(字符串 城市)
        //1,手机号码和城市为必填项
        //2,openid和ip地址 是用来记录用户发送验证码短信的条数, 限制为每天5条
        //3, 如果openid和ip地址都为空, 则用手机号码记录发送次数


        public static bool dkjk_yzm(string city, string phone, string openid, string ip)
        {
            string para = "SendMobileCode?city=" + city + "&mobile=" + phone + "&openid=" + openid + "&ipaddr=" + ip;

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "SendMobileCode";
            yjl.oldurl = para;
            yjl.phone = phone;
            yjl.uid = 0;

            string json = http_dkjk(para,yjl);
            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            return bl;
        }

        public static bool dkjk_yzm_check(string code, string phone, string openid, string ipaddr)
        {
            string para = "CheckMobileCode?code=" + code + "&mobile=" + phone + "&openid=" + openid + "&ipaddr=" + ipaddr;

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "CheckMobileCode";
            yjl.oldurl = para;
            yjl.phone = phone;
            yjl.uid = 0;

            string json = http_dkjk(para, yjl);

            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            //json = Dos.Common.JSON.ToJSON(new { success = bl });
            return bl; // new Jr(json);
        }

        public static Jr dkjk_user_zc(string city, string phone, string xm, string dlm, string mm, string yzm, string openid, string unionId)
        {//mobile(字符串),code(验证码字符串),pwd(登录密码),realname(用户真实姓名或称呼字符串),username(登录名字符串),openid(微信标识),city(城市字符串)
            string para = "Register?source=D几名&city=" + city + "&mobile=" + phone + "&realname=" + xm + "&username=" + dlm + "&pwd=" + mm + "&openid=" + openid + "&code=" + yzm + "&unionid=" + unionId;

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "Register";
            yjl.oldurl = para;
            yjl.phone = phone;
            yjl.uid = 0;

            string json = http_dkjk(para, yjl);

            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            int uid = 0;
            int consume_give_kb = 0;
            int Integral = 0;
            string msg = "";

            if (bl)
            {
                json = jo["data"]["ID"].ToString();
                uid = Convert.ToInt32(json);
            } else {
                msg = jo["msg"].ToString();
            }
            json = Dos.Common.JSON.ToJSON(new { success = bl, uid = uid, openid = openid, kball = consume_give_kb, kbnow = Integral, msg = msg });
            return new Jr(json);
        }

        //每天获取kb
        public static string dkjk_user_upkb(yd_user yu, int kb)
        {
            yd_user_gl yug = get_yd_user_gl(yu.id);
            string json = JSON.ToJSON(new { openid = yug.kqopenid, uid = yug.kquid, kb = kb, date = DateTime.Now.Date, city = yug.city, unionid = yu.unionId });

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "Applet_EveryDayGiveKB";
            yjl.oldurl = json;
            yjl.phone = yug.phone;
            yjl.uid = yu.id;
            yjl.code = yu.code;

            json = Encode(json, "dkdk2017", "abcd2017");
            //string json2 = Decode(json, "dkdk2017", "abcd2017");
            string para = "Applet_EveryDayGiveKB?data=" + System.Web.HttpContext.Current.Server.UrlEncode(json);
            //string para2 = "Applet_EveryDayGiveKB?data=" + System.Web.HttpContext.Current.Server.UrlDecode(json);

            json = http_dkjk(para,yjl);
            //var jo = JObject.Parse(json);
            //bool bl = (bool)jo["result"];
            //bool bl = false;
            //if (json == "1")
            //{
            //    bl = true;
            //}
            return json;
        }

        //额外获取kb
        public static string dkjk_user_up_otherkb(yd_user yu, int kb, string type = "")
        {
            yd_user_gl yug = get_yd_user_gl(yu.id);
            string json = JSON.ToJSON(new { openid = yug.kqopenid, uid = yug.kquid, kb = kb, date = DateTime.Now.Date, city = yug.city, unionid = yu.unionId, type = type });

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "Applet_GoodAreYouGiveKB";
            yjl.oldurl = json;
            yjl.phone = yug.phone;
            yjl.uid = yu.id;
            yjl.code = yu.code;

            json = Encode(json, "dkdk2017", "abcd2017");
            string json2 = Decode(json, "dkdk2017", "abcd2017");
            string para = "Applet_GoodAreYouGiveKB?data=" + System.Web.HttpContext.Current.Server.UrlEncode(json);
            json = http_dkjk(para, yjl);

            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            if (bl == true)
            {
                return "1";
            }
            return "0";
        }


        //同步已近获得的kb
        public static bool dkjk_user_tbkb(yd_user yu, int kb)
        {
            yd_user_gl yug = get_yd_user_gl(yu.id);
            string json = JSON.ToJSON(new { openid = yug.kqopenid, uid = yug.kquid, kb = kb, date = DateTime.Now.Date, city = yug.city, unionid = yu.unionId });

            yd_jk_log yjl = new yd_jk_log();
            yjl.name = "Applet_ApieceGiveKB";
            yjl.oldurl = json;
            yjl.phone = yug.phone;
            yjl.uid = yu.id;
            yjl.code = yu.code;

            json = Encode(json, "dkdk2017", "abcd2017");
            string para = "Applet_ApieceGiveKB?data=" + json;

            json = http_dkjk(para,yjl);
            bool bl = false;
            if (json == "1")
            {
                bl = true;
            }
            return bl;
        }

        //同步已近获得的kb
        public static Jr dkjk_user_kblist(yd_user yu, yd_user_gl yug)
        {
            string para = "Applet_UserKBRecord?city=" + yug.city + "&uid=" + yug.kquid + "&unionid=" + yu.unionId;

            //yd_jk_log yjl = new yd_jk_log();
            //yjl.name = "Applet_ApieceGiveKB";
            //yjl.oldurl = para;
            //yjl.phone = yug.phone;
            //yjl.uid = yu.id;
            //yjl.code = yu.code;

            yd_jk_log yjl = null;
            string json = http_dkjk(para, yjl);
            var jo = JObject.Parse(json);
            bool bl = (bool)jo["result"];
            int uid = 0;
            if (bl)
            {
                json = jo["data"]["rows"].ToString();
                //jo = JObject.Parse(json);
            }

            return new Jr(bl, json, "");
        }

        #endregion

        #region 加密解密对称

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="KEY_64"></param>
        /// <param name="IV_64"></param>
        /// <returns></returns>

        public static string Encode(string data, string KEY_64, string IV_64)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="KEY_64"></param>
        /// <param name="IV_64"></param>
        /// <returns></returns>
        public static string Decode(string data, string KEY_64, string IV_64)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }

        #endregion

        public static string GetRandomString(int iLength)
        {
            string buffer = "0123456789";// 随机字符中也可以为汉字（任何）  
            StringBuilder sb = new StringBuilder();
            Random r = new Random();
            int range = buffer.Length;
            for (int i = 0; i < iLength; i++)
            {
                sb.Append(buffer.Substring(r.Next(range), 1));
            }
            return sb.ToString();
        }

        public static int GetDayPm(int uid)
        {
            //计算团排名
            string sql = string.Format(@" 
                       SELECT pm FROM  
                         (  
                             SELECT A.*,@rank:=@rank+1 AS pm  
                             FROM     
                             (    
                              SELECT  uid,step FROM yd_data_day where udate = '{0}'  ORDER BY step DESC ,id asc  
                             ) A ,(SELECT @rank:=0) B   
                         ) M  where m.uid = {1}
                         ORDER BY m.pm
                        ", DateTime.Now.Date.ToString("yyyy-MM-dd"), uid.ToString());
            object ob = Db.GetDb().FromSql(sql).ToScalar();
            int dpm = 0;
            if (ob != null)
            {
                string s = ob.ToString();
                dpm = Convert.ToInt32(s);
            }
            return dpm;
        }


        #region 更新数据

        public static yd_data_day up_user_runday(int uid, int step, DateTime date, bool blt = false)
        {
            bool bl = false;
            bool bl_insert = false;
            var ydd = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == date).ToFirst();
            try
            {
                if (ydd == null)
                {
                    ydd = new yd_data_day();
                    ydd.kb = 0;
                    ydd.kbdate = DateTime.Now;
                    ydd.udate = date;
                    ydd.uid = uid;
                    ydd.step = step;
                    ydd.kbsum = 0;
                    ydd.id = Db.GetDb().Insert(ydd);
                    bl = true;
                    bl_insert = true;
                }
                else
                {
                    if (step > ydd.step)
                    {
                        ydd.step = step;
                        Db.GetDb().Update(ydd);
                        bl = true;
                    }
                }

                if (bl == true || blt == true)//&& ( ydd.uid == 44 || ydd.uid == 45 )
                {
                    //同步正在参加的图
                    //获取你的正在参加的 还没有结束的团
                    //判断最大的更新时间
                    yd_admin_config ys = KqLogic.get_sysset_self(KqLogic.up_step_max_time);
                    if (ys != null)
                    {
                        //KqLogic.log("up_step_max_time_" + ys.value);
                        double db = Convert.ToDouble(ys.value);
                        DateTime dt1 = DateTime.Now.Date.AddHours(db).AddMinutes(1);
                        //KqLogic.log("up_step_max_time_" + dt1.ToString("yyyy-MM-dd HH:mm:ss"));
                        //KqLogic.log("up_step_max_time_DateTime.Now_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        if (DateTime.Now < dt1)
                        {
                            //KqLogic.log("up_step_max_time_DateTime.Now_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            var where = new Where<yd_data>();
                            where.And<yd_team>((a, b) => a.uid == uid && b.edate >= date && b.bdate <= date);

                            var el_data = Db.GetDb().From<yd_data>()
                                .Select(yd_data._.All)
                                .InnerJoin<yd_team>((a, b) => a.tid == b.id)
                                .Where(where)
                                .ToList();
                            foreach (var item in el_data)
                            {
                                //KqLogic.log("up_step_max_time_3_" + item.id.ToString() + " _ " + item.uid.ToString() );

                                //    //获取当天的跑步数据,初始化
                                //    if (!Assiweb.IsNull(ydd))
                                //    {
                                //        //KqLogic.log("tb_4_" + bl.ToString());
                                //        step = ydd.step;
                                //        yd_data_team ydt = Db.GetDb().From<yd_data_team>().Where(a => a.tid == item.tid && a.uid == uid && a.udate == date).ToFirst();
                                //        if (Assiweb.IsNull(ydt))
                                //        {
                                //            //KqLogic.log("tb_41_" + bl.ToString());
                                //            ydt = new yd_data_team();
                                //            ydt.tid = item.tid;
                                //            ydt.uid = uid;
                                //            ydt.dayid = ydd.id;
                                //            ydt.udate = ydd.udate;
                                //            Db.GetDb().Insert(ydt);
                                //        }
                                //    }

                                //    //统计所有步数的总和
                                //    string sql = string.Format(@" select sum(b.step) as step from yd_data_team a 
                                //    inner join yd_data_day b on a.dayid = b.id 
                                //    where a.tid ={0} and a.uid = {1}
                                //", item.tid.ToString(), ydd.uid.ToString());

                                //    int nbs = Assiweb.GetInt32(Db.GetDb().FromSql(sql).ToScalar().ToString());

                                //KqLogic.log("tb_6_" + nbs);

                                //yd_data yd = Db.GetDb().From<yd_data>().Where(a => a.id == item.id).ToFirst();
                                //KqLogic.log("up_step_max_time_2_" + step);



                                int ce = 0;

                                if (bl_insert == true)
                                {
                                    ce = step;//获取当天的绝对增量
                                }
                                else
                                {
                                    ce = step - (int)item.stepday;//获得增量
                                }

                                item.stepday = step;//最后一次的提交的步数的数据
                                item.udate = ydd.udate;
                                item.step = item.step + ce;
                                Db.GetDb().Update(item);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("team_user_in_131_" + ex.ToString());
            }
            return ydd;
        }

        #endregion

        #region 查询数据

        public static string GetCardMax()
        {
            yd_cardmax yc = Db.GetDb().From<yd_cardmax>().Where(a => a.id == 1).ToFirst();
            string str = (yc.cardmax + 1).ToString();
            char[] sz = str.ToCharArray();
            for (int i = 0; i < sz.Length; i++)
            {
                if (sz[i].ToString() == "4" || sz[i].ToString() == "7")
                {
                    sz[i] = Convert.ToChar((Convert.ToInt32(sz[i].ToString()) + 1).ToString());
                }
            }
            str = new string(sz);
            yc.cardmax = Convert.ToInt32(str);
            Db.GetDb().Update(yc);
            return str;
        }

        public static yd_user Get_User_openid(string openid, string nickName, string imgurl, string unionId,ref int isnew)
        {
            var yd = Db.GetDb().From<yd_user>().Where(d => d.openid == openid).ToFirst();
            if (yd == null)
            {
                yd = new yd_user();
                yd.openid = openid;
                yd.nickname = nickName;
                yd.imgurl = imgurl;
                yd.ydkb = 0;
                yd.isadmin = 0;
                yd.isgl = 0;
                yd.istbkb = 0;
                yd.unionId = unionId;
                yd.credate = DateTime.Now;
                yd.code = KqLogic.GetCardMax();
                yd.id = Db.GetDb().Insert(yd);
                isnew = 1;
            }
            else
            {
                yd.imgurl = imgurl;
                yd.nickname = nickName;
                if (!string.IsNullOrWhiteSpace(unionId))
                {
                    if (string.IsNullOrWhiteSpace(yd.unionId))
                    {
                        yd.unionId = unionId;
                    }
                }
                Db.GetDb().Update(yd);
                isnew = 0;
            }
            return yd;
        }

        public static yd_setting get_sysset()
        {
            yd_setting item = Db.GetDb().From<yd_setting>().Where(d => d.cate == "sys").ToFirst();
            return item;
        }

        public static List<yd_setting> get_sysset_self_array(string name)
        {
            List<yd_setting> item = Db.GetDb().From<yd_setting>().Where(d => d.cate == "self" && d.name == name).ToList();
            return item;
        }

        public static yd_admin_config get_sysset_self(string name)
        {
            yd_admin_config item = Db.GetDb().From<yd_admin_config>().Where(d => d.group == "xcx" && d.name == name).ToFirst();
            if (item == null) {
                KqLogic.log("TemplateTest-111-:" + name);
            }
            return item;
        }

        public static yd_user get_user(int uid)
        {
            return Db.GetDb().From<yd_user>().Where(d => d.id == uid).ToFirst();
        }

        public static yd_user get_user(string openid)
        {
            return Db.GetDb().From<yd_user>().Where(d => d.openid == openid).ToFirst();
        }

        public static yd_user_gl get_yd_user_gl(int uid)
        {
            return Db.GetDb().From<yd_user_gl>().Where(d => d.uid == uid).ToFirst();
        }



        public static Jr Get_List_Team(ComParam param)
        {
            var where = new Where<yd_team>();
           

            

            if (!string.IsNullOrWhiteSpace(param.Mobile))
            {
                where.And(d => d.jstype == KqLogic.jstype_10000);
            }
            else {
                where.And(d => d.isclose == 0);
                DateTime dt2 = DateTime.Now.AddDays(-3);
                where.And(d => d.edate >= dt2);
            }


            if (!string.IsNullOrWhiteSpace(param.Name))
            {
                where.And(d => d.name.Like(param.Name));
            }

            if (!string.IsNullOrWhiteSpace(param.Code))
            {
                DateTime dt = DateTime.Now;

                if (param.Code == "jxz")
                {
                    where.And(d => d.ldate < dt);
                }

                if (param.Code == "yjs")
                {
                    where.And(d => d.ldate >= dt);
                }
            }

            var fs = Db.GetDb(param.city).From<yd_team>()
                //.Select(d => new { d.name, d.bdate, d.edate, d.ldate,d.awardnum,d.peoples,d.usernum })
                .Where(where)
                .OrderBy(yd_team._.isjs.Asc, yd_team._.zdorder.Desc, yd_team._.usernum.Desc, yd_team._.edate.Desc);
            //.OrderByDescending(d => new {d.isjs. d.zdorder, d.usernum, d.edate });


            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }

        public static Jr Get_List_Team_all(ComParam param)
        {
            var where = new Where<yd_team>();
            where.And(a => a.isclose == 0);
            var fs = Db.GetDb(param.city).From<yd_team>()
                //.Select(d => new { d.name, d.bdate, d.edate, d.ldate,d.awardnum,d.peoples,d.usernum })
                .Where(where)
                .OrderByDescending(d => new { d.edate });

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }

        public static Jr Get_List_Team_User_js(ComParam param)
        {
            var team = Db.GetDb().From<yd_team>().Where(a => a.id == param.Id).ToFirst();
            var where = new Where<yd_data_js>();
            where.And(d => d.tid == param.Id && d.credate == DateTime.Now.Date );

            var fs = Db.GetDb(param.city).From<yd_data_js>()
                .Select(yd_data_js._.speed, yd_data_js._.second, yd_data_js._.isend, yd_data_js._.isstart, yd_user._.nickname, yd_user._.imgurl, yd_user_gl._.phone, yd_user._.openid, yd_user._.sdkversion,  yd_user._.unionId,yd_data_js._.startdate)
                .InnerJoin<yd_user>((a, b) => a.uid == b.id)
                .LeftJoin<yd_user_gl>((a, c) => a.uid == c.uid)
                .Where(where)
                .OrderBy(yd_data_js._.isend.Desc && yd_data_js._.enddate.Asc && yd_data_js._.speed.Desc && yd_data_js._.isstart.Desc && yd_data_js._.startdate.Asc)
                ;
            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion


            var list = fs.ToDataTable();
            foreach (DataRow dr in list.Rows)
            {
                int isend = Assiweb.GetDataRowCol<int>(dr, "isend");
                int isstart = Assiweb.GetDataRowCol<int>(dr, "isstart");
                int second = Assiweb.GetDataRowCol<int>(dr, "second");
                decimal speed = Assiweb.GetDataRowCol<decimal>(dr, "speed");
                if (isend == 1)
                {
                    dr["openid"] = "已完成";
                    dr["sdkversion"] = Assiweb.MyDecimalRound(Convert.ToDecimal(speed) * Convert.ToDecimal(3.6)).ToString() + " 公里/小时" ;
                    dr["phone"] = secToTime(second);

                    dr["unionId"] = "red";

                }
                else {
                    dr["phone"] = "";
                    if (team.edate < DateTime.Now)
                    {
                        dr["openid"] = "已超时";
                        dr["sdkversion"] = "--";
                        dr["unionId"] = "gray";
                    }
                    else
                    {
                        if (isstart == 1)
                        {
                            if (team.type == 2)
                            {
                                if (Convert.ToDateTime(dr["startdate"]).AddHours(Convert.ToDouble(team.limithour)) < DateTime.Now)
                                {
                                    dr["openid"] = "已超时";
                                    dr["sdkversion"] = "--";
                                    dr["unionId"] = "gray";
                                }
                                else
                                {
                                    dr["openid"] = "进行中";
                                    dr["sdkversion"] = "--";
                                    dr["unionId"] = "#3bca7a!important";
                                }
                            }
                            else {
                                dr["openid"] = "进行中";
                                dr["sdkversion"] = "--";
                                dr["unionId"] = "#3bca7a!important";
                            }
                            
                        }
                        else
                        {
                            dr["openid"] = "未开始";
                            dr["sdkversion"] = "--";
                            dr["unionId"] = "gray";
                        }
                    }
                }


            }

            return new Jr(true, list, "", dataCount);

        }

        public static Jr Get_List_Team_User(ComParam param)
        {
            var team = Db.GetDb().From<yd_team>().Where(a => a.id == param.Id).ToFirst();
            var where = new Where<yd_data>();
            where.And(d => d.tid == param.Id);
            //&& d.udate <= team.edate && d.udate >= team.bdate
            //种类要做两个处理 

            var fs = Db.GetDb(param.city).From<yd_data>()
                .Select(yd_data._.uid, yd_data._.step, yd_data._.stepday, yd_data._.udate, yd_user._.nickname, yd_user._.imgurl, yd_user_gl._.phone)
                .InnerJoin<yd_user>((a, b) => a.uid == b.id)
                .LeftJoin<yd_user_gl>((a, c) => a.uid == c.uid)
                .Where(where)
                .OrderByDescending(d => new { d.step })
                //.OrderBy(d => new { d.id })
                ;
            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                foreach (DataRow dr in list.Rows)
                {
                    DateTime de = Assiweb.GetDataRowCol<DateTime>(dr, "udate");
                    if (de != DateTime.Now.Date)
                    {
                        dr["stepday"] = 0;
                    }
                }

                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }

        public static String secToTime(int time)
        {
            String timeStr = null;
            int hour = 0;
            int minute = 0;
            int second = 0;
            if (time <= 0)
                return "0'0\"0";
            else
            {
                minute = time / 60;
                if (minute < 60)
                {
                    second = time % 60;
                    timeStr = unitFormat(hour) + "'" + unitFormat(minute) + "\"" + unitFormat(second);
                }
                else
                {
                    hour = minute / 60;
                    if (hour > 99)
                        return "99'59\"59\"";
                    minute = minute % 60;
                    second = time - hour * 3600 - minute * 60;
                    timeStr = unitFormat(hour) + "'" + unitFormat(minute) + "\"" + unitFormat(second);
                }
            }
            return timeStr;
        }

        public static String unitFormat(int i)
        {
            String retStr = null;
            if (i >= 0 && i < 10)
                retStr = i.ToString();
            else
                retStr = "" + i;
            return retStr;
        }


        public static Jr Get_List_Team_User_pm(int tid, int uid)
        {
            string w1 = "";
            string w2 = "";

            string sql = string.Format(@"
            SELECT * from (
                SELECT uid,  (@rownum:=@rownum+1) AS rownum from yd_data ,(SELECT @rownum:= 0 ) r  
		        where tid = {0} ORDER BY step desc 
            ) a  where uid = {1}
            ", tid, uid);
            var list = Db.GetDb().FromSql(sql).ToDataTable();
            string pm = "0";
            if (list != null && list.Rows.Count > 0)
            {
                pm = ((DataTable)list).Rows[0]["rownum"].ToString();
            }
            return new Jr(true, pm, "", 0);

        }

        public static Jr Get_List_Team_User_day(ComParam param, int uid = 0)
        {
            string w2 = "";
            string w3 = "";
            if (uid == 0)
            {
                w2 = " limit " + ((param._PageIndex - 1) * param._PageSize).ToString() + " , " + param._PageSize.ToString() + " ";
            }
            else
            {
                w3 = " where uid = " + uid.ToString();
            }

            string sql = string.Format(@"
SELECT  * from ( 
    SELECT a.*,b.nickname,b.imgurl,(@rownum:=@rownum+1) AS rownum  from (
        SELECT a.uid, IFNULL(b.stepday,0) as stepday ,a.step,a.cdate from yd_data a
        left join (
            SELECT uid,stepday from yd_data where tid ={0} and udate = '{1}'
        ) b on a.uid = b.uid where a.tid = {0}
    ) a
 
    LEFT JOIN yd_user b on a.uid =b.id ,(SELECT @rownum:= 0 ) r 
    ORDER BY stepday desc ,cdate asc {2}
) a {3}
", param.Id, DateTime.Now.ToString("yyyy-MM-dd"), w2, w3);

            //KqLogic.log("Get_List_Team_User_day:" + sql + " _PageSize:" + param._PageSize.ToString() + " _PageIndex:" + param._PageIndex.ToString());
            int dataCount = 0;
            var list = Db.GetDb().FromSql(sql).ToDataTable();
            if (uid > 0)
            {
                string pm = "0";
                if (list != null && list.Rows.Count > 0)
                {
                    pm = ((DataTable)list).Rows[0]["rownum"].ToString();
                }
                return new Jr(true, pm, "", dataCount);
            }

            sql = " select count(*) from yd_data where tid = " + param.Id.ToString();
            object ob = Db.GetDb().FromSql(sql).ToScalar();

            if (ob != null)
            {
                string s = ob.ToString();
                dataCount = Convert.ToInt32(s);
            }
            return new Jr(true, list, "", dataCount);
        }


        public static Jr Get_List_Group_User_day(ComParam param, int gid)
        {

            string sql = string.Format(@"SELECT a.*,b.nickname,b.imgurl from (
SELECT a.uid, IFNULL(b.stepday,0) as stepday ,a.step,a.cdate from yd_data a
left join (
SELECT uid,stepday from yd_data where tid ={0} and gid={4} and udate = '{1}'
) b on a.uid = b.uid where a.tid = {0} and a.gid={4}
) a
LEFT JOIN yd_user b on a.uid =b.id
 ORDER BY stepday desc ,cdate asc limit {2} , {3} ", param.Id, DateTime.Now.ToString("yyyy-MM-dd"), (param._PageIndex - 1) * param._PageSize, param._PageSize, gid);

            var list = Db.GetDb().FromSql(sql).ToDataTable();

            sql = " select count(*) from yd_data where tid = " + param.Id.ToString() + " and gid = " + gid.ToString();
            object ob = Db.GetDb().FromSql(sql).ToScalar();
            int dataCount = 0;
            if (ob != null)
            {
                string s = ob.ToString();
                dataCount = Convert.ToInt32(s);
            }
            return new Jr(true, list, "", dataCount);
        }


        public static Jr Get_List_Group_User(ComParam param, int gid)
        {
            var team = Db.GetDb().From<yd_team>().Where(a => a.id == param.Id).ToFirst();
            var where = new Where<yd_data>();
            where.And(d => d.tid == param.Id && d.gid == gid && d.udate <= team.edate && d.udate >= team.bdate);

            var fs = Db.GetDb(param.city).From<yd_data>()
                .Select(yd_data._.uid, yd_data._.step, yd_data._.stepday, yd_data._.udate, yd_user._.nickname, yd_user._.imgurl)
                .InnerJoin<yd_user>((a, b) => a.uid == b.id)
                .Where(where)
                .OrderByDescending(d => new { d.step })
                ;

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                foreach (DataRow dr in list.Rows)
                {
                    DateTime de = Assiweb.GetDataRowCol<DateTime>(dr, "udate");
                    if (de != DateTime.Now.Date)
                    {
                        dr["stepday"] = 0;
                    }
                }
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }


        //var tj = Db.GetDb().From<yd_data>().Select(d => d.tid).Where(d => d.uid == param.Id && d.isout == 0 ).Distinct().ToList<int>();

        /// <summary>
        /// 用户参与的团
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Jr Get_List_User_Team(ComParam param)
        {
            var where = new Where<yd_team>();
            where.And<yd_data>((a, b) => b.uid == param.Id);
            where.Or(a => a.cuid == param.Id);
            //where.And<table3>((a, c) => c.id == 3);

            var fs = Db.GetDb(param.city).From<yd_team>()
                .Select(a => new { a.id, a.name, a.bdate, a.edate, a.ldate, a.awardnum, a.award, a.peoples, a.usernum, a.cuid, a.isclose, a.clodate, a.pwd })
                .LeftJoin<yd_data>((a, b) => a.id == b.tid);


            if (param.Code == "run")
            {//获取还未结束的跑
                where.And(a => a.ldate > param.Date);
            }
            fs.Where(where);
            fs.Distinct();
            fs.OrderByDescending(d => new { d.ldate });

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }


        public static Jr Get_List_Sqm_admin(ComParam param)
        {
            //Field f1 = new Field("c.nickname as sname");
            var fs = Db.GetDb(param.city).From<yd_key>()
                .Select(yd_key._.All, yd_user._.nickname)
                .LeftJoin<yd_user>((a, b) => a.kuid == b.id)
                .LeftJoin<yd_user>((a, c) => a.syuid == c.id);
            //.Where(where)
            if (param.Code == "sy")
            {//获取还未结束的跑
                fs.Where(a => a.issy == 1);
            }

            if (param.Code == "wy")
            {//获取还未结束的跑
                fs.Where(a => a.issy == 0);
            }

            fs.OrderByDescending(a => new { a.ldate });

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }




        /// <summary>
        /// 用户获取kb的记录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Jr Get_List_User_kb(ComParam param)
        {
            var where = new Where<yd_data_day>();
            where.And(d => d.uid == param.Id);
            if (param.Code == "kb")
            {
                where.And(d => d.kb > 0);
            }

            if (param.Date != null && param.Date > DateTime.MinValue)
            {
                where.And(d => d.udate <= param.Date.Date && d.udate >= param.Date.AddDays(-6).Date);
            }

            var fs = Db.GetDb(param.city).From<yd_data_day>()
                //.Select(d => new { d.kb, d.kbdate, d.udate })
                .Where(where)
                .OrderByDescending(d => new { d.udate });

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }

        /// <summary>
        /// 用户开的团list
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Jr Get_List_User_Team_Admin(ComParam param)
        {
            var fs = Db.GetDb(param.city).From<yd_team>()
                .Select(d => new { d.id, d.name, d.bdate, d.edate, d.ldate, d.awardnum, d.peoples, d.usernum, d.award })
                .Where(a => a.cuid == param.Id);
            fs.OrderByDescending(d => new { d.cdate });

            #region 是否分页
            var dataCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数，以计算共多少页。
                dataCount = fs.Count();
                fs.Page(param._PageSize.Value, param._PageIndex.Value);
            }
            #endregion

            if (param.ToDatatable == 1)
            {
                var list = fs.ToDataTable();
                return new Jr(true, list, "", dataCount);
            }
            else
            {
                var list = fs.ToList();
                return new Jr(true, list, "", dataCount);
            }
        }

        public static Jr Check_sqm(ComParam param)
        {
            yd_key yk = Db.GetDb().From<yd_key>().Where(a => a.key == param.Code).ToFirst();
            if (yk == null)
            {
                return new Jr(21, "1");
            }

            if (yk.issy == 1)
            {
                return new Jr(22, "1");
            }

            if (yk.ldate < DateTime.Now)
            {
                return new Jr(23, "1");
            }

            if (yk.cate != "kt")
            {
                return new Jr(24, "1");
            }

            return new Jr(yk);
        }



        #endregion

        public static bool getMixImage(string newpath, string strBackImage, string strQrcode, int qleft, int qtop, int qw, int qh, string strAvar, int aleft, int atop, int aw, int ah, string name, float tleft, float ttop, string bushu = "", float bleft = 0, float btop = 0, string pm = "", float pleft = 0, float ptop = 0, string kouhao = "", float kleft = 0, float ktop = 0)
        {

            Bitmap background = new Bitmap(strBackImage);
            Bitmap qrImage = new Bitmap(strQrcode);
            Bitmap avImage = new Bitmap(strAvar);
            int iwidth = background.Width;
            int iheight = background.Height;
            Bitmap mixImage2 = new Bitmap(iwidth, iheight);

            try
            {
                float fImage = (float)1;
                Graphics g = Graphics.FromImage(mixImage2);
                float[][] colormatrix ={
                new float[]{1,0,0,0,0},//代表了R                                         
                new float[]{0,1,0,0,0},//代表了G                                         
                new float[]{0,0,1,0,0},//代表了B                                         
                new float[]{0,0,0,fImage,0},//代表了A                                         
                new float[]{0,0,0,0,1}
            };


                ColorMatrix cm = new ColorMatrix(colormatrix);
                ImageAttributes imageAtt = new ImageAttributes();
                imageAtt.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                g.DrawImage(background, new Point(0, 0));

                g.DrawImage(qrImage, new Rectangle(qleft, qtop, qw, qh), 0, 0, qrImage.Width, qrImage.Height, GraphicsUnit.Pixel, imageAtt);

                g.DrawImage(avImage, new Rectangle(aleft, atop, aw, ah), 0, 0, avImage.Width, avImage.Height, GraphicsUnit.Pixel, imageAtt);

                //加文字
                //float textWidth = text.Length * fontSize;  //文本的长度
                //                                           //下面定义一个矩形区域，以后在这个矩形里画上白底黑字
                //                                           //            黑体：SimHei
                //                                           //宋体：SimSun
                //                                           //新宋体：NSimSun
                //                                           //仿宋：FangSong
                //                                           //楷体：KaiTi
                //                                           //仿宋_GB2312：FangSong_GB2312
                //                                           //楷体_GB2312：KaiTi_GB2312
                //                                           //微软雅黑体：Microsoft YaHei

                //float rectWidth = text.Length * (fontSize + 8);
                //float rectHeight = fontSize + 8;
                ////声明矩形域
                //RectangleF textArea = new RectangleF(tleft, ttop, rectWidth, rectHeight);

                float fontSize = 20.0f;             //字体大小
                FontStyle fs = FontStyle.Bold;
                Font font = new Font("微软雅黑体", fontSize, fs);   //定义字体
                Brush whiteBrush = new SolidBrush(Color.White);   //白笔刷，画文字用
                //Brush blackBrush = new SolidBrush(Color.Black);   //黑笔刷，画背景用
                //g.FillRectangle(blackBrush, tleft, ttop, rectWidth, rectHeight);

                float fontSize2 = 16.0f;             //字体大小
                FontStyle fs2 = FontStyle.Bold;
                Font font2 = new Font("微软雅黑体", fontSize2, fs2);   //定义字体


                g.DrawString(name, font2, whiteBrush, tleft, ttop);
                g.DrawString(bushu, font2, whiteBrush, bleft, btop);
                g.DrawString(pm, font2, whiteBrush, pleft, ptop);

                //g.DrawString(kouhao, font, whiteBrush, kleft, ktop);




                mixImage2.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.ToString());
                return false;
            }
            finally
            {
                background.Dispose();
                qrImage.Dispose();
                avImage.Dispose();

                mixImage2.Dispose();
            }
            return true;
        }

        public static bool getMixImage_2(string newpath, string strBackImage, string name, string bushu, string pm, string[] astr, string strQrcode, int iqrw, int iqrh, int iqrwh, string avar, int iavw, int iavh, int iavwh)
        {

            Bitmap background  = null;
            Bitmap mixImage2 = null;
            Bitmap qrImage = null;
            Bitmap qravar = null;

            try
            {
                if (!string.IsNullOrWhiteSpace(strQrcode))
                {
                    qrImage = new Bitmap(strQrcode);
                }
                qravar = new Bitmap(avar);


                background = new Bitmap(strBackImage);

                int iwidth = background.Width;
                int iheight = background.Height;

                mixImage2 = new Bitmap(iwidth, iheight);

                float fImage = (float)1;
                Graphics g = Graphics.FromImage(mixImage2);
                float[][] colormatrix ={
                    new float[]{1,0,0,0,0},//代表了R                                         
                    new float[]{0,1,0,0,0},//代表了G                                         
                    new float[]{0,0,1,0,0},//代表了B                                         
                    new float[]{0,0,0,fImage,0},//代表了A                                         
                    new float[]{0,0,0,0,1}
                };


                string cal = astr[0];
                string ck = astr[1];
                string kb = astr[2];

                g.DrawImage(background, new Point(0, 0));

                ColorMatrix cm = new ColorMatrix(colormatrix);
                ImageAttributes imageAtt = new ImageAttributes();
                imageAtt.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                g.DrawImage(background, new Point(0, 0));
                if (qrImage != null)
                {
                    g.DrawImage(qrImage, new Rectangle(iqrw, iqrh, iqrwh, iqrwh), 0, 0, qrImage.Width, qrImage.Height, GraphicsUnit.Pixel, imageAtt);
                }


                g.DrawImage(qravar, new Rectangle(iavw, iavh, iavwh, iavwh), 0, 0, qravar.Width, qravar.Height, GraphicsUnit.Pixel, imageAtt);

                StringFormat format = new StringFormat();
                //format.LineAlignment = StringAlignment.Center;  // 更正： 垂直居中
                format.Alignment = StringAlignment.Far;      // 水平居中

                StringFormat fc = new StringFormat();
                fc.Alignment = StringAlignment.Center;      // 水平居中

                float f1 = Convert.ToSingle(WebConfigurationManager.AppSettings["f1"].ToString());
                float f2 = Convert.ToSingle(WebConfigurationManager.AppSettings["f2"].ToString());
                float f3 = Convert.ToSingle(WebConfigurationManager.AppSettings["f3"].ToString());
                float f4 = Convert.ToSingle(WebConfigurationManager.AppSettings["f4"].ToString());


                float fontSize = f1;
                FontStyle fs = FontStyle.Bold;//字体大小
                Font font = new Font("微软雅黑体", fontSize, fs);   //定义字体

                float fontSize2 = f2;             //字体大小
                Font font2 = new Font("微软雅黑体", fontSize2, fs);  //定义字体

                float fontSize3 = f3;             //字体大小
                Font font3 = new Font("微软雅黑体", fontSize3);  //定义字体

                float fontSize4 = f4;             //字体大小
                Font font4 = new Font("微软雅黑体", fontSize4);  //定义字体

                Brush whiteBrush = new SolidBrush(Color.White);   //白笔刷，画文字用
                int w = 0;
                int h = 0;

                w = Convert.ToInt32(WebConfigurationManager.AppSettings["name_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["name_h"].ToString());

                int w2 = Convert.ToInt32(WebConfigurationManager.AppSettings["name_font_w"].ToString());
                int h2 = Convert.ToInt32(WebConfigurationManager.AppSettings["name_font_h"].ToString());
                RectangleF textArea = new RectangleF(w, h, w2, h2);

                g.DrawString(name, font4, whiteBrush, textArea, fc);
                //w, h, 

                w = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_h"].ToString());

                g.DrawString(bushu, font2, whiteBrush, w, h);

                w = Convert.ToInt32(WebConfigurationManager.AppSettings["pm_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["pm_h"].ToString());
                g.DrawString(pm, font2, whiteBrush, w, h);


                w = Convert.ToInt32(WebConfigurationManager.AppSettings["cal_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["cal_h"].ToString());
                g.DrawString(cal, font3, whiteBrush, w, h, format);

                w = Convert.ToInt32(WebConfigurationManager.AppSettings["ck_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["ck_h"].ToString());
                g.DrawString(ck, font3, whiteBrush, w, h, format);

                w = Convert.ToInt32(WebConfigurationManager.AppSettings["kb_w"].ToString());
                h = Convert.ToInt32(WebConfigurationManager.AppSettings["kb_h"].ToString());
                g.DrawString(kb, font3, whiteBrush, w, h, format);

                //w = Convert.ToInt32(WebConfigurationManager.AppSettings["qrwwz"].ToString());
                //h = Convert.ToInt32(WebConfigurationManager.AppSettings["qrhwz"].ToString());
                //g.DrawString("长按识别二维码", font4, whiteBrush, w, h, format);

                mixImage2.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.ToString() + ex.Source + ex.StackTrace + ex.Message);
                return false;
            }
            finally
            {
                if (background != null) {
                    background.Dispose();
                }

                if (qrImage != null)
                {
                    qrImage.Dispose();
                }

                if (qravar != null)
                {
                    qravar.Dispose();
                }

                if (mixImage2 != null)
                {
                    mixImage2.Dispose();
                }
                
            }
            return true;
        }

        public static bool getMixImage_3(string newpath, string strBackImage, string name, string bushu,  string strQrcode, int iqrw, int iqrh, int iqrwh, string avar, int iavw, int iavh, int iavwh, int zl = 0, int my=0)
        {

            Bitmap background = null;
            Bitmap mixImage2 = null;
            Bitmap qrImage = null;
            Bitmap qravar = null;

            try
            {

                if (!string.IsNullOrWhiteSpace(strQrcode))
                {
                    try
                    {
                        qrImage = new Bitmap(strQrcode);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(" getMixImage_3 - qrImage " + ex.ToString() + ex.Source + ex.StackTrace + ex.Message);
                    }
                }

                try
                {
                    qravar = new Bitmap(avar);
                }
                catch (Exception ex)
                {
                    qravar = null;
                    LogHelper.Error(" getMixImage_3 - qravar " + ex.ToString() + ex.Source + ex.StackTrace + ex.Message);
                }

                int iwidth = 375;
                int iheight = 667;

                try
                {
                    background = new Bitmap(strBackImage);
                    iwidth = background.Width;
                    iheight = background.Height;
                }
                catch (Exception ex)
                {
                    background = null;
                    LogHelper.Error(" getMixImage_3 - background " + ex.ToString() + ex.Source + ex.StackTrace + ex.Message);
                }

                mixImage2 = new Bitmap(iwidth, iheight);

                float fImage = (float)1;
                Graphics g = Graphics.FromImage(mixImage2);
                float[][] colormatrix ={
                    new float[]{1,0,0,0,0},//代表了R                                         
                    new float[]{0,1,0,0,0},//代表了G                                         
                    new float[]{0,0,1,0,0},//代表了B                                         
                    new float[]{0,0,0,fImage,0},//代表了A                                         
                    new float[]{0,0,0,0,1}
                };
                
                ColorMatrix cm = new ColorMatrix(colormatrix);
                ImageAttributes imageAtt = new ImageAttributes();
                imageAtt.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                if (background != null)
                {
                    g.DrawImage(background, new Point(0, 0));
                }

                if (qrImage != null)
                {
                    g.DrawImage(qrImage, new Rectangle(iqrw, iqrh, iqrwh, iqrwh), 0, 0, qrImage.Width, qrImage.Height, GraphicsUnit.Pixel, imageAtt);
                }


                if (my > 0)
                {
                    if (qravar != null)
                    {
                        g.DrawImage(qravar, new Rectangle(iavw, iavh, iavwh, iavwh), 0, 0, qravar.Width, qravar.Height, GraphicsUnit.Pixel, imageAtt);
                    }
                }

                StringFormat format = new StringFormat();
                //format.LineAlignment = StringAlignment.Center;  // 更正： 垂直居中
                format.Alignment = StringAlignment.Far;      // 水平居中


                StringFormat fc = new StringFormat();
                fc.Alignment = StringAlignment.Center;      // 水平居中

                Brush whiteBrush = new SolidBrush(Color.White);   //白笔刷，画文字用
                if (my > 0)
                {
                    float f1 = Convert.ToSingle(WebConfigurationManager.AppSettings["f1_10000"].ToString());
                    float f2 = Convert.ToSingle(WebConfigurationManager.AppSettings["f2_10000"].ToString());
                    float f3 = Convert.ToSingle(WebConfigurationManager.AppSettings["f3_10000"].ToString());

                    float fontSize = f1;
                    FontStyle fs = FontStyle.Bold;//字体大小
                    Font font = new Font("微软雅黑体", fontSize, fs);   //定义字体

                    float fontSize2 = f2;             //字体大小
                    Font font2 = new Font("微软雅黑体", fontSize2, fs);  //定义字体

                    float fontSize3 = f3;             //字体大小
                    Font font3 = new Font("微软雅黑体", fontSize3);  //定义字体

                    
                    int w = 0;
                    int h = 0;
                    int w2 = 0;
                    int h2 = 0;

                    int w3 = 0;
                    int h3 = 0;

                    int wn = 0;
                    int hn = 0;

                    float fontn = Convert.ToSingle(WebConfigurationManager.AppSettings["fn_10000"].ToString());
                    float fontSizen = fontn;             //字体大小
                    Font fontnn = new Font("微软雅黑体", fontSizen);  //定义字体

                    wn = Convert.ToInt32(WebConfigurationManager.AppSettings["name_w_10000"].ToString());
                    hn = Convert.ToInt32(WebConfigurationManager.AppSettings["name_h_10000"].ToString());

                    int wn2 = Convert.ToInt32(WebConfigurationManager.AppSettings["name_font_w_10000"].ToString());
                    int hn2 = Convert.ToInt32(WebConfigurationManager.AppSettings["name_font_h_10000"].ToString());
                    RectangleF textArea = new RectangleF(wn, hn, wn2, hn2);
                    g.DrawString(name, fontnn, whiteBrush, textArea, fc);


                    w = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_w_10000"].ToString());
                    h = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_h_10000"].ToString());

                    w2 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_w2_10000"].ToString());
                    h2 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_h2_10000"].ToString());

                    g.DrawString("今日步数", font, whiteBrush, w2, h2);
                    g.DrawString(bushu, font2, whiteBrush, w, h);

                    if (my == 10000)
                    {
                        w3 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_w3_10000"].ToString());
                        h3 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_h3_10000"].ToString());
                        g.DrawString(zl.ToString(), font3, whiteBrush, w3, h3);
                    }
                }
                else {
                    float f4 = Convert.ToSingle(WebConfigurationManager.AppSettings["f4_10000"].ToString());
                    float fontSize = f4;
                    FontStyle fs = FontStyle.Bold;//字体大小
                    Font font = new Font("微软雅黑体", fontSize, fs);   //定义字体
                    int w4 = 0;
                    int h4 = 0;

                    w4 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_w4_10000"].ToString());
                    h4 = Convert.ToInt32(WebConfigurationManager.AppSettings["bushu_h4_10000"].ToString());

                    g.DrawString(bushu, font, whiteBrush, w4, h4);
                }


                mixImage2.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.ToString() + ex.Source + ex.StackTrace + ex.Message);
                return false;
            }
            finally
            {
                if (background != null)
                {
                    background.Dispose();
                }

                if (qrImage != null)
                {
                    qrImage.Dispose();
                }

                if (qravar != null)
                {
                    qravar.Dispose();
                }

                if (mixImage2 != null)
                {
                    mixImage2.Dispose();
                }

            }
            return true;
        }

        /// <summary>  
        /// 下载网络图片   
        /// </summary>  
        /// <param name="PicSourceUrl">图片的网络地址</param>  
        /// <param name="filePath">图片保存在本地的路径（需要加上图片的保存名称 如：D:\Images\1.jpg）</param>  
        /// <returns></returns>  
        public static bool DownPic(string PicSourceUrl, string filePath)
        {
            try {
                if (System.IO.File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
            catch
            {
                return false;
            }

            WebRequest request = null;
            WebResponse response = null;
            Stream reader = null;

            try
            {
                request = WebRequest.Create(PicSourceUrl);
                response = request.GetResponse();
                reader = response.GetResponseStream();

                using (FileStream writer = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buff = new byte[512];
                    int c = 0; //实际读取的字节数  
                    while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                    {
                        writer.Write(buff, 0, c);
                    }
                    writer.Close();
                    writer.Dispose();
                    reader.Close();
                    reader.Dispose();
                    response.Close();
                    response.Dispose();
                }
            }
            catch
            {
                return false;
            }
            finally
            {

                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                }
            }

            return true;
        }

        public static int InsTm(int uid, string frmid)
        {
            //时间戳
            int id = 0;
            //新增frmid
            DateTime dt = DateTime.Now;
            
            var item = new yd_user_tm();
            item.uid = uid;
            item.frmid = frmid;
            item.cdate = ConvertDateTimeInt(dt.Date);
            item.ctime = ConvertDateTimeInt(dt);
            item.stime = dt;
            id = Db.GetDb().Insert(item);

            //删除过期的 id 
            DateTime dt2 = dt.AddDays(-7);
            int gq = ConvertDateTimeInt(dt2);
            Db.GetDb().Delete<yd_user_tm>(a => a.uid == uid && a.ctime <= gq);

            return id;
        }

        public static string GetTm(int uid)
        {
            //时间戳
            string frmid = "";
            //新增frmid
            DateTime dt = DateTime.Now;
            DateTime dt2 = dt.AddDays(-7);
            int gq = ConvertDateTimeInt(dt2);
            var item = Db.GetDb().From<yd_user_tm>().Where(a => a.uid == uid && a.ctime >= gq).OrderBy(a => a.id).ToFirst();
            if (item != null)
            {
                Db.GetDb().Delete(item);
                frmid = item.frmid;
            }
            return frmid;
        }


        /// <summary>  
        /// 将Unix时间戳格式转换为c# DateTime时间格式  
        /// </summary>  
        /// <param name="timeStamp">时间戳</param>  
        /// <returns>DateTime </returns>  
        public static DateTime GetTime(int timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp.ToString() + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>double</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (int)(time - startTime).TotalSeconds;
            return intResult;
        }

        public static int ConvertDateTimeInt()
        {
            System.DateTime time = DateTime.Now;
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (int)(time - startTime).TotalSeconds;
            return intResult;
        }


        public static void SendTm_team_createor(yd_team yt)
        {
            //200 这个值 要读取数据库  而且已经发送过一次 就不再发送了
            var ys = Assiweb.GetInt32(get_sysset_self(tm_team_usernum_1).value);
            if (yt.usernum > ys && yt.istmnum == 0)
            {
                string page = "";
                bool bl = SendTm_common_team_tz(yt.cuid, yt.id, tm_team_usernum_1, "", "");
                yt.istmnum = 1;
                Db.GetDb().Update(yt);
            }
        }

        public static WxJsonResult SendTemplateMessage(string accessTokenOrAppId, string openId, string templateId,
           object data, string formId, string page)
        {
            return ApiHandlerWapper.TryCommonApi(accessToken =>
            {
                //                const string urlFormat = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={0}";
                //                var msgData = new Senparc.Weixin.WxOpen.AdvancedAPIs.Template
                //.TempleteModel()
                //                {
                //                    touser = openId ,
                //                    template_id = templateId,
                //                    page = page,
                //                    form_id = formId,
                //                    data = data,
                //                    emphasis_keyword = null
                //                };

                //var data2 = new WxOpenTemplateMessage_PaySuccessNotice(
                //"在线购买", DateTime.Now, "图书众筹", "1234567890",
                //100, "400-9939-858", "http://sdk.senparc.weixin.com");


                //var result = TemplateApi.SendTemplateMessage(_wxOpenAppId, openId, data2.TemplateId, data, "formSubmit", "pages/websocket",
                //"keyword3");
                //result.

                WxJsonResult wj = new WxJsonResult(); //Senparc.Weixin.WxOpen.AdvancedAPIs.MessageApi.SendSubscribe()

                //WxJsonResult wj = Senparc.Weixin.MP.CommonAPIs.CommonApi.Send<WxJsonResult>(accessToken, urlFormat, msgData,Senparc.Weixin.CommonJsonSendType.POST, timeOut: 10000);

                return wj;

            }, accessTokenOrAppId);
        }


        public static bool SendTm_common(string formId, string openid, string page, WxOpenTemplateMessage_PaySuccessNotice data, ref string msg)
        {
            try
            {
                bool blf = false;
                string so = WebConfigurationManager.AppSettings["openid"].ToString();
                if (string.IsNullOrWhiteSpace(so))
                {
                    blf = true;
                }
                else if (so.IndexOf(openid) > -1)
                {
                    blf = true;
                }
                else
                {
                    msg = "openid丢失";
                    blf = false;
                }
                if (blf == true)
                {
                    //Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(AppId, openid, data.TemplateId, data, formId, page);
                    try
                    {
                        KqLogic.log("SendTemplateMessage:" + data.TemplateId + "_" + page, "SendTemplateMessage_");
                        msg = "ok";
                        WxJsonResult wj = SendTemplateMessage(AppId, openid, data.TemplateId, data, formId, page);
                        if (!Assiweb.StrIsEmpty(wj.ErrorCodeValue.ToString()))
                        {
                            msg = wj.ErrorCodeValue.ToString() + "-" + wj.errcode.ToString() + "-" + wj.errmsg.ToString();
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        msg = "wx_error_" + ex.Message;
                        KqLogic.log("SendTemplateMessage_error_:" + ex.Message.ToString() + "_" + page, "SendTemplateMessage_");
                        return false;
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                KqLogic.log("TemplateTest-error:" + ex.Message);
                msg = "common_error_" + ex.Message;
                return false;
                //return new Jr(false, ex.Message, ex.Message);
            }
        }

        public static WxOpenTemplateMessage_PaySuccessNotice get_10000_wp(int uid, int tid, ref string sreturnbac)
        {
            var data = new WxOpenTemplateMessage_PaySuccessNotice("", DateTime.Now, "", "", 100, "", "");

            //判断用户的 签到情况
            int qdc = 0;
            var qd = Db.GetDb().From<yd_data_qd>().Where(a => a.tid == tid && a.uid == uid && a.credate == DateTime.Now.Date).ToFirst();

            int step = 0;
            var ydd = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == DateTime.Now.Date).ToFirst();
            if (ydd != null)
            {
                step = ydd.step;
            }
            string sreturn = "今天开始！";

            if (qd != null)
            {
                qdc = Convert.ToInt32(qd.dqqd);
                if (qdc == KqLogic.qdday_10)
                {
                    //模板ID B_5IGo_cTqT - HX_MaldBjmizX5WUTL5dsIl4cGKLu8s
                    //标题
                    //运动结果通知
                    //昨日步数 xxxxx
                    //系统通知 恭喜完成“每天一万步”挑战！继续加油，保持这份冲劲和坚持！未来没有什么能够难倒你！

                    data.TemplateId = "B_5IGo_cTqT-HX_MaldBjmizX5WUTL5dsIl4cGKLu8s";
                    data.keyword1 = new TemplateDataItem(step.ToString());//昵称
                    sreturn = "恭喜完成“每天一万步”挑战！继续加油，保持这份冲劲和坚持！未来没有什么能够难倒你！";
                    data.keyword2 = new TemplateDataItem(sreturn);//获取积分
                    sreturnbac = "打卡第7天";
                }
                else
                {
                    data.TemplateId = "tdAXusJsA7yArB9Ie1b_swb9a6WVsieuCc5elzUtgtw";
                    data.keyword1 = new TemplateDataItem("每天一万步");//昵称
                    data.keyword2 = new TemplateDataItem("今日步数" + step.ToString());//获取积分
                    sreturn = "加油！打卡第" + qdc.ToString() + "天";
                    sreturnbac = "打卡第" + qdc.ToString() + "天";
                    data.keyword3 = new TemplateDataItem(sreturn);//获取积分
                }
            }
            else
            {

                if (step == 0)
                {
                    data.TemplateId = "B_5IGo_cTqT-HX_MaldBjmizX5WUTL5dsIl4cGKLu8s";
                    data.keyword1 = new TemplateDataItem("0");//昵称
                    sreturn = "好可惜！今天没能获取到您的步数进行打卡，一定记得进入程序刷新步数哦！";
                    data.keyword2 = new TemplateDataItem(sreturn);//获取积分
                }
                else
                {
                    data.TemplateId = "tdAXusJsA7yArB9Ie1b_swb9a6WVsieuCc5elzUtgtw";
                    data.keyword1 = new TemplateDataItem("每天一万步");//昵称
                    data.keyword2 = new TemplateDataItem("今日步数" + step.ToString());//获取积分

                    string s = KqLogic.get_sysset_self(KqLogic.fxstep_10000).value;
                    int fxstep = Assiweb.GetInt32(s);
                    step = fxstep - step;
                    sreturn = "还差" + step.ToString() + "步，查看“我的状态”，生成图片让好友助力200步哦！";
                    data.keyword3 = new TemplateDataItem(sreturn);//获取积分
                }

                var qd2 = Db.GetDb().From<yd_data_qd>().Where(a => a.tid == tid && a.uid == uid && a.credate == DateTime.Now.AddDays(-1).Date).ToFirst();
                if (qd2 != null)
                {
                    qdc = Convert.ToInt32(qd2.dqqd);

                }
                sreturnbac = "打卡第" + qdc.ToString() + "天";
            }
            return data;
        }

        public static bool SendTm_common_team_tz_10000(int uid, int tid, string key, string page, string remark, string pm = "")
        {
            var it = KqLogic.get_user(uid);
            string openid = it.openid;
            string formId = KqLogic.GetTm(it.id);
            if (!Check_formid(formId))
            {
                KqLogic.log("TemplateTest-10000-:" + formId);
                return false;
            }

            page = "pages/team/main?tid=" + tid.ToString();
            bool bl = false;
            string st = "";
            var data = get_10000_wp(uid, tid, ref st);
            string msg = "";
            bl = SendTm_common(formId, openid, page, data,ref msg);
            return bl;
        }

        public static int SendTm_common_team_tz_dh(yd_user yu, WxOpenTemplateMessage_PaySuccessNotice data, string page, ref string msg)
        {
            string openid = yu.openid;
            string formId = KqLogic.GetTm(yu.id);
            if (!Check_formid(formId))
            {
                KqLogic.log("TemplateTest-dh-:" + formId);
                msg = "formid不足,不能发送";
                return -2;
            }
            //string page = "pages/index/index?dh=1";
            bool bl = false;
            string st = "";
            bl = SendTm_common(formId, openid, page, data, ref msg);
            if (bl == false)
            {
                return -1;
            }
            return 0;
        }

        public static bool SendTm_common_team_tz_join_10000(int uid, int tid, string key, string page, string remark, string pm = "")
        {
            try
            {
                var it = KqLogic.get_user(uid);
                string openid = it.openid;
                string formId = KqLogic.GetTm(it.id);
                if (!Check_formid(formId))
                {
                    KqLogic.log("TemplateTest-1-:" + formId);
                    return false;
                }

                page = "pages/team/main?tid=" + tid.ToString();
                var data = new WxOpenTemplateMessage_PaySuccessNotice("", DateTime.Now, "", "", 100, "", "");
                bool bl = false;

                data.TemplateId = "I9kayUERwVIy3KLwmQbOfJ6t-MqS_0MO4xz-nD-7TRg";

                data.keyword1 = new TemplateDataItem("每天一万步");//昵称
                data.keyword2 = new TemplateDataItem(key);//获取积分
                data.keyword3 = new TemplateDataItem("连续7天打卡每天一万步！不积跬步，无以至千里。一万步没有你想象的那么难哦！");//总可用积分
                string msg = "";
                bl = SendTm_common(formId, openid, page, data,ref msg);
                return bl;
            }
            catch (Exception ex)
            {
                KqLogic.log("SendTm_common_team_tz_join_10000-error:" + ex.Message);
                return false;
            }
        }

        public static bool SendTm_common_team_tz(int uid, int tid,string key, string page, string remark,string pm="")
        {
            try
            {
                var it = KqLogic.get_user(uid);
                string openid = it.openid;
                string formId = KqLogic.GetTm(it.id);
                if (!Check_formid(formId))
                {
                    KqLogic.log("TemplateTest-1-:" + formId);
                    return false;
                }

                var data = new WxOpenTemplateMessage_PaySuccessNotice("", DateTime.Now, "", "", 100, "", "");
                bool bl = false;
                if (key == fxjl)
                {
                    data.TemplateId = "nkHUqyaDOkgcPd13S8ELpv8wZ8Of6__UIfHK6hpPmOk";

                    data.keyword1 = new TemplateDataItem(remark);//昵称
                    data.keyword2 = new TemplateDataItem(tid.ToString());//获取积分
                    data.keyword3 = new TemplateDataItem(pm);//总可用积分
                    string msg2 = "";
                    bl = SendTm_common(formId, openid, page, data, ref msg2);
                    return bl;
                }



                var team = Db.GetDb().From<yd_team>().Where(a => a.id == tid).ToFirst();
                //if (team == null) {
                //    return false;
                //} 


                if (string.IsNullOrWhiteSpace(page) || page == "")
                {
                    page = "pages/team/main?tid=" + tid.ToString();
                }

                if (key == timer_bsjs_js)
                {
                    //获取remark
                    remark = "加油！本次竞赛排名第" + pm + "名。感谢您的参与，点击生成海报分享您的成绩，“每一步，都算数！”";
                }

                if (key == KqLogic.tm_team_userin && team.type == 1)
                {
                    remark = "欢迎加入！比赛开始时间：" + team.bdate.ToString("yyyy年MM月dd日HH时mm分") + "。从" + team.qdname + team.qdaddr + "起，至" + team.zdname + team.zdaddr + "结束。";
                }

                //KqLogic.log("TemplateTest-3-:" + key);

                if (remark == "")
                {
                    remark = Get_Tm_selfString(key, team, pm);
                }

                //KqLogic.log("TemplateTest-4-:" + remark);


                data.TemplateId = "m458_Xf_1A3zFkT008cBJTRVrP3vnIj7FRBvfhfJ9YE";
                data.keyword3 = new TemplateDataItem(remark);

                int days = 0;
                if (team != null)
                {
                    DateTime dtime1 = Convert.ToDateTime(team.edate.Date);
                    DateTime dtime2 = Convert.ToDateTime(DateTime.Now.Date);
                    TimeSpan s = dtime1 - dtime2;
                    days = Convert.ToInt32(s.TotalDays);//到了 就是0天
                }


                if (team != null)
                {
                    if (team.type == 0)
                    {
                        data.keyword1 = new TemplateDataItem(team.name + "(步数竞赛)");
                        if (days > 0)
                        {
                            data.keyword2 = new TemplateDataItem(days.ToString() + "天");
                        }
                        else
                        {
                            data.keyword2 = new TemplateDataItem("已结束");
                        }
                    }
                    else
                    {
                        data.keyword1 = new TemplateDataItem(team.name + "(速度竞赛)");
                        DateTime dtime1 = Convert.ToDateTime(team.edate);
                        DateTime dtime2 = Convert.ToDateTime(DateTime.Now);
                        TimeSpan s = dtime1 - dtime2;
                        days = Convert.ToInt32(s.TotalSeconds);//到了 就是0天
                        if (days > 0)
                        {
                            string st = DateDiff(DateTime.Now, team.edate);
                            data.keyword2 = new TemplateDataItem(st);
                        }
                        else
                        {
                            data.keyword2 = new TemplateDataItem("已结束");
                        }
                    }
                }
                else
                {
                    data.keyword1 = new TemplateDataItem("D几名温馨提醒");
                    data.keyword2 = new TemplateDataItem("");
                }
                //KqLogic.log("TemplateTest-5-:" + data.TemplateId);

                if (key == timer_nodk_time)
                {
                    data.keyword1 = new TemplateDataItem("0");//昨日步数
                    data.keyword2 = new TemplateDataItem(remark);
                    data.TemplateId = "B_5IGo_cTqT-HX_MaldBjmizX5WUTL5dsIl4cGKLu8s";
                }


                string msg = "";
                bl = SendTm_common(formId, openid, page, data,ref msg);
                //Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(AppId, openid, data.TemplateId, data, formId, page);
                return bl;
            }
            catch (Exception ex)
            {
                KqLogic.log("TemplateTest-error:" + ex.Message);
                return false;
            }
        }

        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                string hours = ts.Hours.ToString(), minutes = ts.Minutes.ToString(), seconds = ts.Seconds.ToString();
                if (ts.Hours < 10)
                {
                    hours = "0" + ts.Hours.ToString();
                }
                if (ts.Minutes < 10)
                {
                    minutes = "0" + ts.Minutes.ToString();
                }
                if (ts.Seconds < 10)
                {
                    seconds = "0" + ts.Seconds.ToString();
                }
                dateDiff = hours + "小时" + minutes + "分";
            }
            catch
            {

            }
            return dateDiff;
        }

        public static bool SendTm_team_edit(int uid,string page,yd_team yt)
        {
            var it = KqLogic.get_user(uid);
            string formId = KqLogic.GetTm(it.id);
            if (!Check_formid(formId))
            {
                return false;
            }

            var data = new WxOpenTemplateMessage_PaySuccessNotice("", DateTime.Now, "", "", 100, "", "");
            data.TemplateId = "rIAyJ7HwULLluLC4e5vbUmCvn4OwVdWNrUqPZRNWYjE";

            string title = "";
            string b = yt.bdate.ToString("yyyy年MM月dd日");
            string e = yt.edate.ToString("yyyy年MM月dd日");

            if (yt.type == 0)
            {
                title = yt.name.Trim() + "(步数竞赛)";
            }
            else
            {
                title = yt.name.Trim() + "(速度竞赛)";
                b = yt.bdate.ToString("yyyy年MM月dd日 HH:MM");
                e = yt.edate.ToString("yyyy年MM月dd日 HH:MM");
            }

            TemplateDataItem td1 = new TemplateDataItem(title);
            TemplateDataItem td2 = new TemplateDataItem(b + "-" + e);

            //分组名称 
            string g = "";
            string r = "无通告";

            if (yt.type == 0)
            {
                List<yd_group> list = Db.GetDb().From<yd_group>().Where(d => d.tid == yt.id).ToList();
                foreach (yd_group yg in list)
                {
                    g += " " + yg.name;
                }
                if (g.Length == 0)
                {
                    g = "无分组";
                }
                else
                {
                    g = g.Remove(0, 1);
                }

                if (!string.IsNullOrWhiteSpace(yt.remark))
                {
                    r = yt.remark;
                }
            }
            else
            {
                g = "";
                if (!string.IsNullOrWhiteSpace(yt.remark))
                {
                    r = yt.remark;
                }
            }

            TemplateDataItem td3 = new TemplateDataItem(g.Trim());
            TemplateDataItem td4 = new TemplateDataItem(r.Trim());

            data.keyword1 = td1;
            data.keyword2 = td2;
            data.keyword3 = td3;
            data.keyword4 = td4;
            string msg = "";
            bool bl = SendTm_common(formId, it.openid, page, data,ref msg);
            return bl;
        }

        public static string tm_team_usernum_1 = "tm_team_usernum_1";
        public static string tm_team_usernum_2 = "tm_team_usernum_2";
        public static string tm_team_usernum_1_txt = "tm_team_usernum_1_txt";
        public static string tm_team_usernum_2_txt = "tm_team_usernum_2_txt";

        public static string timer_2day_time = "timer_2day_time";
        public static string timer_2day_txt = "timer_2day_txt";
        

        public static string tm_team_userin = "tm_team_userin";

        public static string kbdays = "kbdays";

        public static string fxjl = "fxjl";//这里感觉没有用 用户获取不到那么多的消息key

        public static string kbdays_zskb = "kbdays_zskb";

        public static string timer_nodk_time = "timer_nodk_time";
        public static string timer_nodk_txt = "timer_nodk_txt";

        public static string timer_bsjs_time = "timer_bsjs_time";
        public static string timer_bsjs_txt = "timer_bsjs_txt";

        public static string timer_bsjsq_time = "timer_bsjsq_time";
        public static string timer_bsjsq_txt = "timer_bsjsq_txt";

        public static string timer_bsjs_js = "timer_bsjs_js";
        
        public static string Get_Tm_selfString(string key, yd_team yt,string pm="")
        {
            //根据key 获取数据库的 匹配值 以及替换数值
            // #pm#

            //var item = get_sysset_self(key);//.text1;
            //if (item != null) {
            //     re = item.value;
            //}
            //if (re == "") {
            //    return "";
            //}

            //恭喜！你的竞赛人数达到了#竞赛人数#人！达到#竞赛礼品人数#人时便可向DK申请认领该竞赛的奖品。蛋糕、泡芙、冰淇淋等免费奖品可以让你的小伙伴更嗨哟！加油吧！
            //恭喜！你的竞赛达到了免费申请奖品的人数！请联系DK小客服，微信DK_dijiming，我们的工作人员将会为你安排奖品事宜。
            //好可惜！昨天没能获取到你的步数，今天一定记得进入比赛刷新步数哦！
            //加油！本次竞赛总排名第#竞赛排名#名！感谢你的参与，点击生成海报分享你的成绩，“每一步，都算数”！
            //你的竞赛当前加入人数#竞赛人数#人，分享竞赛页面到微信群中，让更多的小伙伴加入进来吧！
            //比赛明天就结束啦，当前总排名第#竞赛排名#名，明天请继续加油！
            // 欢迎加入！记得每天都要进入竞赛刷新步数，不然当天的步数可能为0哟！

            string re = "";
            //系统触发
            if (key == tm_team_usernum_1)
            {
                //string[] sArray = Regex.Split(re, "###", RegexOptions.IgnoreCase);
                int day2 = Convert.ToInt32(get_sysset_self(tm_team_usernum_2).value);
                if (yt.usernum >= day2)
                {
                    re = get_sysset_self(tm_team_usernum_2_txt).value;
                    re = re.Replace("#竞赛礼品人数#", yt.usernum.ToString());
                }
                else
                {
                    re = get_sysset_self(tm_team_usernum_1_txt).value;
                    re = re.Replace("#竞赛人数#", yt.usernum.ToString());
                    re = re.Replace("#竞赛礼品人数#", day2.ToString());
                }
            }
            else if (key == tm_team_userin)
            {
                re = get_sysset_self(tm_team_userin).value;
                //欢迎加入！记得每天都要进入竞赛刷新步数，不然当天的步数可能为0哟！
            }
            //定时器触发
            else if (key == timer_2day_time)
            {
                re = get_sysset_self(timer_2day_txt).value;
                KqLogic.log("Get_Tm_selfString_" + re);
                re = re.Replace("#竞赛人数#", yt.usernum.ToString());
                KqLogic.log("Get_Tm_selfString_" + re);
                //欢迎加入！记得每天都要进入竞赛刷新步数，不然当天的步数可能为0哟！
            }
            else if (key == timer_nodk_time)
            {
                re = get_sysset_self(timer_nodk_txt).value;
            }
            else if (key == timer_bsjs_time)
            {
                re = get_sysset_self(timer_bsjs_txt).value;
                KqLogic.log("Get_timer_bsjs_txt_" + re);
                re = re.Replace("#竞赛排名#", pm);
            }
            else if (key == timer_bsjsq_time)
            {
                re = get_sysset_self(timer_bsjsq_txt).value;
                re = re.Replace("#竞赛排名#", pm);
            }

            return re;
        }

        public static bool Check_formid(string fid)
        {
            if (!Assiweb.StrIsEmpty(fid) && fid != "the formId is a mock one")//
            {
                return true;
            }
            return false;
        }

        public static int[] Get_Kb_Days(int uid)
        {
            int[] arri = new int[] { 0, 0 };
            //连续几天打卡了
            int day = Assiweb.GetInt32(get_sysset_self(kbdays).value);
            if (day == 0)
            {
                return arri;
            }
            day = day - 1;
            DateTime dt = DateTime.Now.Date;
            DateTime dt2 = dt.AddDays(-1 * day);
            //这个时间段内, 如果查询出 能够获取kb的天数一致,那么表示 连续几天打开了.
            // 这里有个问题啊  连续几天的事情比较难以定夺
            var list = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.step1 > 0 && a.udate >= dt2 && a.udate <= dt && a.dkday == 0).ToList().Count();
            if (list > day)
            {
                int zskb = Assiweb.GetInt32(get_sysset_self(kbdays_zskb).value);
                var item = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == dt).ToFirst();
                if (item != null)
                {
                    item.dkday = day + 1;


                    //看看是否要多送
                    if (zskb > 0)
                    {
                        //需要多送,调用接口
                        yd_user yu = KqLogic.get_user(uid);
                        string res = KqLogic.dkjk_user_up_otherkb(yu, zskb);

                        if (res == "0")
                        {
                            item.zskb = -1;
                        }
                        else if (res == "1")
                        {
                            item.zskb = zskb;
                        }
                        else
                        {
                            item.zskb = -2;
                        }
                    }
                    Db.GetDb().Update(item);
                }
                //同步数据库 记录签到打开了
                arri = new int[] { item.dkday, zskb };
                return arri;
            }
            return arri;
        }


    }
}
